<?php

class Default_CartController extends Zend_Controller_Action
{

    public function init()
    {
        
    }

    public function indexAction()
    {
        $this->view->headTitle("Cart")->setSeparator(" | ");
        $cart = new Zend_Session_Namespace("cart");
        $this->view->cart = $cart;
    }

    public function addAction()
    {        
        $mdProd = new Application_Model_DbTable_Product();
        $id = $this->_request->getParam("id");
        $prod = $mdProd->find($id)->current();
        $cart = new Zend_Session_Namespace("cart");     
        if($prod)
        {
            // Tang tong so luong
            $qty = $this->_request->getParam("qty",1);
            $total = $cart->total + $qty;
            $cart->total = $total;
            
            //Neu da co sp trong gio hang thi cap nhat
            if(isset($cart->items[$id]))
            {
                $cart->items[$id]['qty'] = $cart->items[$id]['qty'] + $qty;
            }
            else
            {
                $cart->items[$id] = array(
                    "qty" => $qty,
                    "prod" => $prod
                ); 
            }
                       
            $this->_helper->json->sendJson($cart->total);  
        }
        else
        {
            $this->_helper->json->sendJson(false);    
        }
    }

    public function checkoutAction()
    {
        
        $this->view->headScript()->appendFile(
            $this->view->baseUrl("templates/admin/js/jquery.validate.min.js")
        );
        
        if($this->_request->isPost())
        {
            $username = $this->_request->getParam("username", "");
            $password = $this->_request->getParam("password", "");
            if($username!="")            
            {
                
                $auth = Zend_Auth::getInstance();
                $autAdapter = new Zend_Auth_Adapter_DbTable(null, "customers", "username", "password");            
                $autAdapter->setIdentity($username)
                           ->setCredential(md5($password));
                $select = $autAdapter->getDbSelect();
                $select->where("status=?",1);                
                $result = $auth->authenticate($autAdapter);                
                if($result->isValid())
                {
                    $store = $auth->getStorage();
                    $store->write($autAdapter->getResultRowObject(array(
                        "id","username","fullname","email","address","phone","intro"
                    )));
                }   
                else
                {
                    $this->view->has_err = "Username or Password is Incorrect!";
                }
            }
            else
            {
                $this->view->has_err = "Username or Password is Incorrect!";
            }
            
        }   
        $cart = new Zend_Session_Namespace("cart");
        $aut = Zend_Auth::getInstance();
        $this->view->isLogin = $aut->hasIdentity();        
        $this->view->customer = $aut->getIdentity();
        
        $this->view->cart = $cart->items;   
        $this->view->total = $cart->total;   
        
    }
    
    public function  processOrderAction()
    {
        $mdHistory = new Application_Model_DbTable_OrderHistory();
        $fullname = $this->_request->getParam("fullname");
        $email = $this->_request->getParam("email");
        $address = $this->_request->getParam("address");
        $phone = $this->_request->getParam("phone");
        
        if($fullname!="" && $email != "" && $address != "")
        {
            //Save to database and send mail
            $mdOrder = new Application_Model_DbTable_Order();
            $row = $mdOrder->createRow();
            $cart = new Zend_Session_Namespace("cart");
            $row->quantity = $cart->total;
            if(count($cart->items)>0)
            {
                $total_price = 0;
                foreach($cart->items as $item)
                {
                    $total_price += $item['qty'] * $item['prod']->price;
                }
                
                $row->total_price = $total_price;
                $row->created_date = date("Y-m-d H:i:s");
                $aut = Zend_Auth::getInstance();
                if($aut->hasIdentity())
                {
                    $row->customers = $aut->getIdentity()->id;
                }
                $row->fullname = $fullname;
                $row->email = $email;
                $row->address = $address;
                $row->phone = $phone;
                $idorder = $row->save();
                
                $nid = $rowDetail->save();
                $mdHistory = new Application_Model_DbTable_OrderHistory();
                $row_history = $mdHistory->createRow(array(
                    "date"=> date("Y-m-d H:i:s"),
                    "comment"=>"",
                    "notify_customer"=>1,
                    "orders_id"=>$nid,
                    "status_id"=>1
                ));
                $row_history->save();
                
                // Luu chi tiet don dat hang
                $mdOrderDetail = new Application_Model_DbTable_OrderDetail();
                foreach($cart->items as $item){
                    $rowDetail = $mdOrderDetail->createRow(array(
                        "orders_id" => $idorder,
                        "products_id" => $item['prod']->id,
                        "qty" => $item['qty']
                    ));
                }
                
                // Send mail
                $mailbody .= 
                    "<div>Thank you for ...</div>
                    <p><strong>Full name:</strong>$row->fullname</p>
                    <p><strong>Email:</strong>$row->email</p>
                    <p><strong>Address:</strong>$row->address</p>
                    <p><strong>Phone:</strong>$row->phone</p>
                    ";
                    
                // chi tiet don ahng
                $mailbody .= 
                "<table style='width: 100%;'>
                    <thead style='background:#ccc'>
                        <tr>
                            <th align='center'>Item Code</th>
                            <th align='center'>Product Name</th>
                            <th align='center'>Price</th>
                            <th align='center'>Quantity</th>
                            <th align='center'>Total Price</th>
                        </tr>
                    </thead>
                    
                    <tbody>";
                                                        
                        $sum = 0; 
                        foreach($cart->items as $row){ 
                            $prod = $row['prod'];
                            $total_price = number_format($row['qty']*$prod->price,2,".","");
                            $price = number_format($prod->price,2,".","");
                            
                            $mailbody .=
                            "<tr>
                                <td  style='border:1px solid #ccc'>$prod->code</td>
                                <td  style='border:1px solid #ccc'>$prod->name</td>
                                <td  style='border:1px solid #ccc'>$ {$price}</td>
                                <td  style='border:1px solid #ccc'>$row[qty]</td>
                                <td  style='border:1px solid #ccc'>$ $total_price</td>
                            </tr>";
                            $sum += $row['qty']*$prod->price;
                        }
                        $sum = number_format($sum,2,".","");
               $mailbody .=   
                    "</tbody>    
                    <tfoot>
                        <tr>
                            <td colspan='4' style='font-weight: bold; border:1px solid #ccc;'>Sum</td>
                            <td  style='border:1px solid #ccc'>$ $sum</td>
                        </tr>
                    </tfoot>
                </table>";
                
                $result = Cms_Mail_Smtp::send(
                    array("username"=>"kiet.vo@non.vn","password"=>"k20460077","server"=>"smtp.gmail.com"),
                    array("address"=>"kiet.vo@non.vn","name"=>"tvoshopee.com"),
                    array("address"=>$email,"name"=>"Mail send to customer"),
                    "Order detail in tvoshopee.com website",
                    $mailbody
                );
                
                //Xoa session order
                Zend_Session::namespaceUnset("cart");
                $cart = new Zend_Session_Namespace("cart");
                if(!isset($cart->total)){
                    $cart->total = 0;
                    $cart->items = array();    
                }
            }        
        }
        
        
    }


    public function editAction()
    {
        $id = $this->_request->getParam("id");
        $cart = new Zend_Session_Namespace("cart");
        $sum = 0;
        if(key_exists($id,$cart->items))
        {
            $qty = $this->_request->getParam("qty",0);
            if($qty>=0)
            {
                $temp = $qty - $cart->items[$id]['qty']; 
                $cart->items[$id]['qty'] = $qty;
                $cart->total = $cart->total + $temp;
            }
            
            foreach($cart->items as $row)
            {
                $sum += $row['qty'] * $row['prod']->price;
            }
        }
        
        $this->_helper->json->sendJson(array(
            "total"=>$cart->total,
            "total_price"=>"$".number_format($cart->items[$id]['qty']*$cart->items[$id]['prod']->price,2,".",""),
            "sum" => "$".number_format($sum,2,".","")
        ));
    }
    
    public function delAction()
    {
        $id = $this->_request->getParam("id", null);
        $cart = new Zend_Session_Namespace("cart");
        $sum = 0;
        if(key_exists($id,$cart->items))
        {
            
            $cart->total -= $cart->items[$id]['qty'];
            unset($cart->items[$id]);
        }
        
        foreach($cart->items as $row)
        {
            $sum = $row['qty'] * $row['prod']->price;
        }
        
        $this->_helper->json->sendJson(array("total"=>$cart->total,"sum"=>$sum));        
    }
    
    public function listAction()
    {
        $cart = new Zend_Session_Namespace("cart");
        $this->view->cart = $cart->items;
    }

}













